<template>
  <div class="modal-wrap">
    <a-form-model
      layout="horizontal"
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 18 }"
      class="content"
    >
      <a-form-model-item
        v-for="(item, index) in newFormKey"
        :key="index"
        :label="item.title"
        :prop="item.key"
      >
        <template v-if="item.view === 'sel_search'">
          <a-select
            :disabled="disableStatus(item.key)"
            :value="formData[item.key]"
            show-search
            placeholder="请选择"
            option-filter-prop="children"
            style="width: 100%"
            :filter-option="filterOption"
            @change="(e) => onChange(e, item.key)"
          >
            <a-select-option
              v-for="key in option"
              :key="key.id"
              :value="key.id"
            >
              {{ key.roleCode }}
            </a-select-option>
          </a-select>
        </template>
        <template v-else-if="item.view === 'datetime'">
          <a-date-picker
            show-time
            :disabled="disableStatus(item.key)"
            :value="formData[item.key]"
            format="YYYY-MM-DD HH:mm:ss"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
            placeholder="请选择"
            @change="(e) => onChange(e, item.key)"
          />
        </template>
        <template v-else-if="item.view === 'cat_tree'">
          <a-tree-select
            :disabled="disableStatus(item.key)"
            :value="formData[item.key]"
            style="width: 100%"
            :tree-data="treeData"
            placeholder="请选择"
            :maxTagCount="1"
            showSearch
            treeCheckable
            treeCheckStrictly
            treeNodeFilterProp="title"
            @change="(val) => selectTreeChange(val, item.key)"
          ></a-tree-select>
        </template>
        <template v-else-if="item.view === 'radio'">
          <a-radio-group
            :disabled="disableStatus(item.key)"
            :value="formData[item.key]"
            @change="(e) => onChange(e.target.value, item.key)"
          >
            <a-radio :value="1">正常</a-radio>
            <a-radio :value="2">冻结</a-radio>
          </a-radio-group>
        </template>
        <template v-else-if="item.view === 'textarea'">
          <a-textarea
            :disabled="disableStatus(item.key)"
            placeholder="请输入"
            :value="formData[item.key]"
            @change="(e) => onChange(e.target.value, item.key)"
            :autoSize="{ minRows: 2, maxRows: 4 }"
          />
        </template>
        <template v-else-if="item.view === 'passWord'">
          <a-input-password
            :disabled="disableStatus(item.key)"
            placeholder="请输入"
            :value="formData[item.key]"
            @change="(e) => onChange(e.target.value, item.key)"
          ></a-input-password>
        </template>
        <template v-else-if="item.view === 'text_number'">
          <a-input-number
            :disabled="disableStatus(item.key)"
            :min="1"
            style="width: 100%"
            placeholder="请输入"
            :value="formData[item.key]"
            @change="(e) => onChange(e, item.key)"
          ></a-input-number>
        </template>
        <template v-else>
          <a-input
            :disabled="disableStatus(item.key)"
            placeholder="请输入"
            :value="formData[item.key]"
            @change="(e) => onChange(e.target.value, item.key)"
          ></a-input>
        </template>
      </a-form-model-item>
    </a-form-model>
    <div class="my-btn" v-show="!disable">
      <a-button type="primary" @click="submit">保存</a-button>
      <a-button @click="offModal">取消</a-button>
    </div>
  </div>
</template>
<script setup>
import { ref, computed } from "vue";
import { checkCode } from "@/services/userManage.service";
const props = defineProps({
  formKey: {
    type: Array,
  },
  option: {
    type: Array,
  },
  treeData: {
    type: Array,
  },
  formData: {
    type: Object,
  },
  title: {
    type: String,
  },
  tableName: {
    type: String,
  },
  editNameBack: {
    type: String,
  },
  disable: {
    type: Boolean,
    default: false,
  },
});
const ruleForm = ref(null);
const emit = defineEmits([
  "updateFormData",
  "offModalOperation",
  "submitModal",
]);
function disableStatus(key) {
  let status = props.disable;
  if (key === "username" && !props.title.includes("新增")) {
    status = true;
  } else if (key === "editor") {
    status = true;
  }
  return status;
}
function onChange(value, key) {
  emit("updateFormData", key, value);
}
function selectTreeChange(value, key) {
  if (value.length > 1) {
    emit("updateFormData", key, []);
    setTimeout(() => {
      emit("updateFormData", key, value.slice(1));
    }, 300);
  } else {
    emit("updateFormData", key, []);
    setTimeout(() => {
      emit("updateFormData", key, value);
    }, 300);
  }
}
function filterOption(input, option) {
  return (
    option.componentOptions.children[0].text
      .toLowerCase()
      .indexOf(input.toLowerCase()) >= 0
  );
}
async function checkName(value, callback) {
  let params = {
    tableName: props.tableName,
    fieldName: props.formKey[0].key,
    fieldVal: value,
  };
  await checkCode(params).then((res) => {
    if (res.code !== 200) {
      callback(new Error(res?.message || "校验失败"));
    } else {
      return true;
    }
  });
}
async function validateKpiCode(rule, value, callback) {
  if (value) {
    // 这里要区分新增额编辑操作。编辑的时候要做名称备份，允许不修改名称
    if (props.title.includes("修改")) {
      if (props.editNameBack === value) {
        return true;
      } else {
        await checkName(value, callback);
      }
    } else {
      await checkName(value, callback);
    }
  } else {
    callback(new Error("请输入"));
  }
}
const newFormKey = computed(() => {
  let arr = [];
  if (props.title.includes("新增")) {
    arr = props.formKey;
  } else {
    arr = props.formKey.filter((item) => item.view !== "passWord");
  }
  return arr;
});
const rules = computed(() => {
  let obj = {};
  if (props.formKey.length > 0) {
    if (!props.title.includes("查看")) {
      props.formKey.forEach((item, index) => {
        if (item.view === "text") {
          if (index === 0) {
            obj[item.key] = [
              { required: true, validator: validateKpiCode, trigger: "blur" },
            ];
          } else {
            obj[item.key] = [
              { required: true, message: "请输入", trigger: "change" },
            ];
          }
        } else if (item.view === "passWord") {
          if (item.key === "confirmPassword") {
            obj[item.key] = [
              { required: true, validator: validatePassWord, trigger: "blur" },
            ];
          } else {
            obj[item.key] = [
              { required: true, message: "请输入", trigger: "blur" },
            ];
          }
        } else if (item.view.includes("cat_tree")) {
          obj[item.key] = [
            { required: true, message: "请选择", trigger: "blur" },
          ];
        } else if (item.view === "text_number") {
          obj[item.key] = [
            { required: true, validator: validatePhone, trigger: "blur" },
          ];
        } else {
          obj[item.key] = [
            { required: true, message: "请选择", trigger: "change" },
          ];
        }
      });
    } else {
      props.formKey.forEach((item) => {
        obj[item.key] = [
          { required: true, message: "请选择", trigger: "change" },
        ];
      });
    }
  }
  return obj;
});
function validatePhone(rule, value, callback) {
  if (value) {
    if (value.toString().length !== 11) {
      callback(new Error("手机号码格式错误,11位纯数字"));
    } else {
      return true;
    }
  } else {
    callback(new Error("请输入手机号码"));
  }
}
function validatePassWord(rule, value, callback) {
  if (value) {
    if (props.formData.password === value) {
      return true;
    } else {
      callback(new Error("两次输入的密码不一致"));
    }
  } else {
    callback(new Error("请再次输入密码"));
  }
}
function submit(e) {
  e.preventDefault();
  ruleForm.value.validate((valid) => {
    if (valid) {
      emit("submitModal");
    }
  });
}
function offModal() {
  emit("offModalOperation");
}
</script>
<style scoped lang="less">
.modal-wrap {
  width: 100%;
  .my-btn {
    width: 100%;
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 40px;
  }
}
/deep/ .ant-row.ant-form-item.ant-form-item-with-help {
  margin-bottom: 0;
}
/deep/ .ant-row.ant-form-item {
  margin-bottom: 22px;
}
</style>
